package game.leon.war.gate;

import game.leon.engine.net.GateMessageHandler;
import game.leon.engine.net.GateSession;
import game.leon.engine.net.codec.GateRawMessage;
import game.leon.engine.utils.Reciever;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * User: bianpeng
 * Date: 12-1-10
 */
@Component
public class GateReciever implements GateMessageHandler {
    private Logger logger = Logger.getLogger(getClass());
    // 事件队列
    private Reciever<GateMessage> reciever = new Reciever<GateMessage>();
    @Autowired
    private GateConsumer gateConsumer;
    @PostConstruct
    public void init() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(;;) {
                    if (reciever.isEmpty()) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            logger.error("sleep failed", e);
                        }
                    } else {
                        gateConsumer.consume(reciever.consume());
                    }
                }
            }
        }).start();
    }
    @Override
    public void execute(GateSession session, GateRawMessage message) {
        reciever.recieve(new GateMessage(session, message));
    }
}
